<template>
  <div class="marketing-notification">
    <!-- 搜索筛选 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="消息类型">
          <el-select v-model="searchForm.type" placeholder="请选择" clearable>
            <el-option label="系统通知" value="system" />
            <el-option label="营销推广" value="marketing" />
            <el-option label="订单提醒" value="order" />
            <el-option label="活动通知" value="activity" />
          </el-select>
        </el-form-item>
        <el-form-item label="发送状态">
          <el-select v-model="searchForm.status" placeholder="请选择" clearable>
            <el-option label="待发送" value="pending" />
            <el-option label="发送中" value="sending" />
            <el-option label="发送成功" value="sent" />
            <el-option label="发送失败" value="failed" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作工具栏 -->
    <div class="toolbar">
      <el-button type="primary" @click="handleCreate">新建消息</el-button>
    </div>

    <!-- 消息列表 -->
    <el-card class="table-card">
      <el-table v-loading="loading" :data="tableData" border stripe>
        <el-table-column prop="title" label="消息标题" min-width="200" />
        <el-table-column prop="type" label="消息类型" width="100">
          <template #default="{ row }">
            <el-tag>{{ getTypeText(row.type) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="targetType" label="推送对象" width="100">
          <template #default="{ row }">
            {{ getTargetText(row.targetType) }}
          </template>
        </el-table-column>
        <el-table-column prop="totalCount" label="推送数量" width="100" />
        <el-table-column prop="successCount" label="成功数量" width="100" />
        <el-table-column prop="status" label="发送状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160" />
        <el-table-column prop="sendTime" label="发送时间" width="160" />
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button type="text" size="small" @click="handleView(row)">查看</el-button>
            <el-button 
              v-if="row.status === 'pending'" 
              type="text" 
              size="small" 
              @click="handleSend(row)"
            >
              发送
            </el-button>
            <el-popconfirm title="确定删除该消息吗？" @confirm="handleDelete(row)">
              <template #reference>
                <el-button type="text" size="small" style="color: #f56c6c;">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="loadTableData"
          @size-change="loadTableData"
        />
      </div>
    </el-card>

    <!-- 消息表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="新建消息"
      width="800px"
    >
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px">
        <el-form-item label="消息类型" prop="type">
          <el-select v-model="formData.type" style="width: 100%;">
            <el-option label="系统通知" value="system" />
            <el-option label="营销推广" value="marketing" />
            <el-option label="订单提醒" value="order" />
            <el-option label="活动通知" value="activity" />
          </el-select>
        </el-form-item>
        <el-form-item label="消息标题" prop="title">
          <el-input v-model="formData.title" placeholder="请输入消息标题" />
        </el-form-item>
        <el-form-item label="消息内容" prop="content">
          <el-input v-model="formData.content" type="textarea" :rows="4" />
        </el-form-item>
        <el-form-item label="推送对象" prop="targetType">
          <el-radio-group v-model="formData.targetType">
            <el-radio label="all">全部用户</el-radio>
            <el-radio label="vip">VIP用户</el-radio>
            <el-radio label="new">新用户</el-radio>
            <el-radio label="active">活跃用户</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="发送方式">
          <el-checkbox-group v-model="formData.channels">
            <el-checkbox label="app">APP推送</el-checkbox>
            <el-checkbox label="sms">短信通知</el-checkbox>
            <el-checkbox label="email">邮件通知</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="定时发送">
          <el-switch v-model="formData.scheduled" />
          <el-date-picker
            v-if="formData.scheduled"
            v-model="formData.scheduleTime"
            type="datetime"
            placeholder="选择发送时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="margin-left: 10px;"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button @click="handleSaveDraft">保存草稿</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          {{ formData.scheduled ? '定时发送' : '立即发送' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 消息详情对话框 -->
    <el-dialog v-model="viewDialogVisible" title="消息详情" width="600px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="消息标题">{{ currentMessage.title }}</el-descriptions-item>
        <el-descriptions-item label="消息类型">{{ getTypeText(currentMessage.type) }}</el-descriptions-item>
        <el-descriptions-item label="推送对象">{{ getTargetText(currentMessage.targetType) }}</el-descriptions-item>
        <el-descriptions-item label="发送状态">{{ getStatusText(currentMessage.status) }}</el-descriptions-item>
        <el-descriptions-item label="推送数量">{{ currentMessage.totalCount }}</el-descriptions-item>
        <el-descriptions-item label="成功数量">{{ currentMessage.successCount }}</el-descriptions-item>
        <el-descriptions-item label="创建时间" :span="2">{{ currentMessage.createTime }}</el-descriptions-item>
        <el-descriptions-item label="发送时间" :span="2">{{ currentMessage.sendTime }}</el-descriptions-item>
      </el-descriptions>
      <div style="margin-top: 20px;">
        <h4>消息内容</h4>
        <p>{{ currentMessage.content }}</p>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getNotificationList, sendNotification, updateNotification, deleteNotification } from '@/api/wash_service'

export default {
  name: 'MarketingNotification',
  setup() {
    const loading = ref(false)
    const submitLoading = ref(false)
    const dialogVisible = ref(false)
    const viewDialogVisible = ref(false)
    const formRef = ref()

    const searchForm = reactive({
      type: '',
      status: ''
    })

    const pagination = reactive({
      current: 1,
      size: 20,
      total: 0
    })

    const tableData = ref([])
    const currentMessage = ref({})

    const formData = reactive({
      type: '',
      title: '',
      content: '',
      targetType: 'all',
      channels: ['app'],
      scheduled: false,
      scheduleTime: ''
    })

    const formRules = {
      type: [{ required: true, message: '请选择消息类型', trigger: 'change' }],
      title: [{ required: true, message: '请输入消息标题', trigger: 'blur' }],
      content: [{ required: true, message: '请输入消息内容', trigger: 'blur' }],
      targetType: [{ required: true, message: '请选择推送对象', trigger: 'change' }]
    }

    const typeMap = {
      system: '系统通知',
      marketing: '营销推广',
      order: '订单提醒',
      activity: '活动通知'
    }

    const targetMap = {
      all: '全部用户',
      vip: 'VIP用户',
      new: '新用户',
      active: '活跃用户'
    }

    const statusMap = {
      pending: { text: '待发送', type: 'warning' },
      sending: { text: '发送中', type: 'primary' },
      sent: { text: '发送成功', type: 'success' },
      failed: { text: '发送失败', type: 'danger' }
    }

    const getTypeText = (type) => typeMap[type] || type
    const getTargetText = (target) => targetMap[target] || target
    const getStatusText = (status) => statusMap[status]?.text || status
    const getStatusType = (status) => statusMap[status]?.type || 'default'

    const loadTableData = async () => {
      loading.value = true
      try {
        const res = await getNotificationList({
          page: pagination.current,
          size: pagination.size,
          ...searchForm
        })
        
        if (res && (res.code === 200 || res.data || res.content)) {
          const data = res.data || res
          tableData.value = data.content || data.records || data || []
          pagination.total = data.totalElements || data.total || 0
        } else {
          tableData.value = []
          pagination.total = 0
        }
      } catch (error) {
        console.error('获取通知列表失败:', error)
        ElMessage.warning('获取通知列表失败，请检查网络连接')
        tableData.value = []
        pagination.total = 0
      } finally {
        loading.value = false
      }
    }

    const handleSearch = () => {
      pagination.current = 1
      loadTableData()
    }

    const handleReset = () => {
      Object.assign(searchForm, { type: '', status: '' })
      handleSearch()
    }

    const handleCreate = () => {
      resetFormData()
      dialogVisible.value = true
    }

    const handleView = (row) => {
      currentMessage.value = row
      viewDialogVisible.value = true
    }

    const handleSend = async (row) => {
      try {
        await ElMessageBox.confirm('确定立即发送该消息吗？', '提示', {
          type: 'warning'
        })
        
        const res = await sendNotification({
          id: row.id,
          action: 'send'
        })
        
        if (res && (res.code === 200 || res.success)) {
          ElMessage.success('消息发送成功')
          loadTableData()
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('发送消息失败:', error)
          ElMessage.error('发送失败')
        }
      }
    }

    const handleDelete = async (row) => {
      try {
        const res = await deleteNotification(row.id)
        if (res && (res.code === 200 || res.success)) {
          ElMessage.success('删除成功')
          loadTableData()
        }
      } catch (error) {
        console.error('删除通知失败:', error)
        ElMessage.error('删除失败')
      }
    }

    const handleSaveDraft = async () => {
      try {
        const res = await sendNotification({
          ...formData,
          status: 'draft'
        })
        
        if (res && (res.code === 200 || res.success)) {
          ElMessage.success('草稿保存成功')
          dialogVisible.value = false
          loadTableData()
        }
      } catch (error) {
        console.error('保存草稿失败:', error)
        ElMessage.error('保存失败')
      }
    }

    const handleSubmit = async () => {
      if (!formRef.value) return
      
      try {
        await formRef.value.validate()
        submitLoading.value = true
        
        const res = await sendNotification({
          ...formData,
          status: formData.scheduled ? 'scheduled' : 'pending'
        })
        
        if (res && (res.code === 200 || res.success)) {
          ElMessage.success(formData.scheduled ? '定时发送设置成功' : '消息发送成功')
          dialogVisible.value = false
          loadTableData()
        }
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error('操作失败')
      } finally {
        submitLoading.value = false
      }
    }

    const resetFormData = () => {
      Object.assign(formData, {
        type: '',
        title: '',
        content: '',
        targetType: 'all',
        channels: ['app'],
        scheduled: false,
        scheduleTime: ''
      })
    }

    onMounted(() => {
      loadTableData()
    })

    return {
      loading,
      submitLoading,
      dialogVisible,
      viewDialogVisible,
      formRef,
      searchForm,
      pagination,
      tableData,
      currentMessage,
      formData,
      formRules,
      getTypeText,
      getTargetText,
      getStatusText,
      getStatusType,
      loadTableData,
      handleSearch,
      handleReset,
      handleCreate,
      handleView,
      handleSend,
      handleDelete,
      handleSaveDraft,
      handleSubmit
    }
  }
}
</script>

<style scoped>
.marketing-notification {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.toolbar {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style> 